package com.rjkj.medicalwaste.viewmodels

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSONObject
import com.rjkj.medicalwaste.base.BaseViewModel
import com.rjkj.medicalwaste.bean.SqlInfoBean
import com.rjkj.medicalwaste.database.MainDatabase
import com.rjkj.medicalwaste.network.response.deal
import com.rjkj.medicalwaste.network.response.next
import com.rjkj.medicalwaste.network.retrofit.Api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class MainViewModel(private val database: MainDatabase) : BaseViewModel() {

    //
//    fun start() {
//        viewModelScope.launch(IO) {
//            flow {
//
//                while (true) {
//                    val deal = requestSimple {
//                        getSqlInfo(deviceSN = serialNum)
//                    }.deal()
//                    if (deal != null) {
//                        emit(deal)
//                    }
//                    delay(3 * 1000)
//                }
//            }.catch { e ->
//                Log.e(TAG, "Caught $e")
//            }.collectLatest {
//                for (value in it) {
//                    try {
//                        database.runInTransaction {
//                            database.openHelper.writableDatabase.execSQL(value.sqlStatement)
//                        }
//                        requestExecSqlResult(no = value.no, result = 0)
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                        requestExecSqlResult(no = value.no, result = 1)
//                    }
//
//                }
//            }
//        }
//    }

    suspend fun requestExecSqlResult(url: String = "", no: String, result: Int) {
        request {
            execSqlResult(url = url, no = no, result = result)
        }
    }

    suspend fun requestHistoryInfoLoopData(url: String, deviceSN: String, nowVersion: String) {
        request(false) {
            val json = JSONObject()
            json["nowVersion"] = nowVersion
            json["deviceSN"] = deviceSN
            historyInfo(url = url, jsonObject = json)
        }
    }

    suspend fun requestSqlInfoLoopData(url: String, deviceSN: String): List<SqlInfoBean>? {
        return try {
            requestSimple {
                getSqlInfo(url = url, deviceSN = deviceSN)
            }.deal()
        } catch (e: Throwable) {
            listOf()
        }
    }
}